package server

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"qiniupkg.com/x/log.v7"
)

type infoForApp struct {
	Page        string    `bson:"page" json:"page,omitempty"`               // 是哪个界面操作的
	Address     string    `bson:"address" json:"address,omitempty"`         // 请求的ip地址
	RequestTime time.Time `bson:"requestTime" json:"requestTime,omitempty"` // 请求的时间
}

func AppInfo(w http.ResponseWriter, r *http.Request) {
	body, err := ioutil.ReadAll(r.Body)

	if err != nil {
		w.Write([]byte("read body error"))
		return
	}
	info := new(infoForApp)

	err = json.Unmarshal(body, info)
	if err != nil {
		w.Write([]byte("unmarshal error"))
		return
	}

	info.RequestTime = time.Now()
	info.Address = r.RemoteAddr
	session, err := mgo.Dial("mongodb://roy:123456@118.25.56.118:27017")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	c := session.DB("test1").C("auditInfo")

	err = c.Insert(info)
	if err != nil {
		log.Debugf("insert error :%v", err)
	}
	// test()
	w.Write([]byte("success"))
}

type Person struct {
	Name  string
	Phone string
}

func test() {
	session, err := mgo.Dial("mongodb://roy:123456@118.25.56.118:27017")
	if err != nil {
		panic(err)
	}

	defer session.Close()
	session.SetMode(mgo.Monotonic, true)

	c := session.DB("test").C("auditInfo")

	err = c.Insert(&Person{"张乐", "14755117607"}, &Person{"李白", "14755117607"})

	if err != nil {
		panic(err)
	}

	result := Person{}

	err = c.Find(bson.M{"name": "张乐"}).One(&result)

	if err != nil {
		panic(err)
	}

	fmt.Println(result.Phone)

}
